package de.trebings.gia.servlets;

import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.http.*;

import org.json.JSONException;

import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.types.User;

import de.trebings.gia.util.PMF;
import de.trebings.gia.util.UserManager;

@SuppressWarnings("serial")
public abstract class AbstractAdminServlet extends HttpServlet {

	PersistenceManager pm;
	UserManager um;
	FacebookClient facebookClient;
	String serverName;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		System.out.println("Servlet: " + this.getServletName() + " started (GET)");
		pm = PMF.get().getPersistenceManager();
		um = new UserManager(pm, req.getSession());
		serverName = req.getServerName();
		try {
			processGet(req, resp);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		pm.close();
		System.out.println("Servlet: " + this.getServletName() + " ended");
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		System.out.println("Servlet: " + this.getServletName() + " started (POST)");
		pm = PMF.get().getPersistenceManager();
		um = new UserManager(pm, req.getSession());
		serverName = req.getServerName();
		try {
			processPost(req, resp);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		pm.close();
		System.out.println("Servlet: " + this.getServletName() + " ended");
	}

	protected boolean isAuthorized(String accessToken) {
		boolean result = false;

		// for local testing return always true
		if("localhost".equals(serverName)){
			return true;
		}
		
		// for productive work, check facebook email address
		// currrently only allow christian.trebing@gmx.de to do changes
		if(facebookClient == null){
			facebookClient = new DefaultFacebookClient(accessToken);
		}
		com.restfb.types.User fbUser = facebookClient.fetchObject("me", com.restfb.types.User.class);

		if ("christian.trebing@gmx.de".equals(fbUser.getEmail())) {
			result = true;
		}
		
		return result;
	}

	public abstract void processGet(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, JSONException;

	public abstract void processPost(HttpServletRequest req,
			HttpServletResponse resp) throws IOException, JSONException;

}
